package com.example.spring.security.demo.component;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;

/**
 * @ClassName MyAuthorityCheck
 * @Description
 * @Author lichuanqi
 * @Date 2022/5/17 11:19
 * @Version 1.0
 **/
@Component("ex")
public class MyAuthorityCheck {

    public boolean hasAuthority(String authority){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        if (CollectionUtils.isEmpty(authorities)){
            return false;
        }

        for (GrantedAuthority grantedAuthority : authorities) {
            if (authority.equals(grantedAuthority.getAuthority())){
                return true;
            }
        }

        return false;
    }
}
